package com.zy.common.core.domain;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.annotation.ExcelIgnore;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.zy.common.core.domain.model.LoginUser;
import com.zy.common.helper.LoginHelper;
import lombok.Data;
import org.hibernate.annotations.Comment;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.UpdateTimestamp;
import org.springframework.data.annotation.CreatedDate;
import org.springframework.data.annotation.LastModifiedDate;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;

import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;

/**
 * 基本实体
 */
@Data
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public class BaseEntity implements Serializable {
    @Id
    @GeneratedValue(
        generator = "system-uuid"
    )
    @GenericGenerator(
        name = "system-uuid",
        strategy = "uuid"
    )
    @Comment(value = "id")
    @ExcelIgnore
    private String id;

    @ExcelIgnore
    @Comment(value = "创建人")
    private Long createBy;

    @ExcelIgnore
    @CreatedDate
    @Comment(value = "创建时间")
    private LocalDateTime createTime = LocalDateTime.now();

    @ExcelIgnore
    @UpdateTimestamp
    @Comment(value = "最后更新时间")
    @LastModifiedDate
    @OrderBy
    private LocalDateTime updateTime = LocalDateTime.now();

    @ExcelIgnore
    @Comment(value = "最后更新人")
    private Long updateBy;

    @Comment("是否删除")
    @Column(name = "deleted",columnDefinition = "bit default 0")
    @ExcelIgnore
    @TableLogic(value = "false", delval = "true")
    private Boolean deleted = false;

    @PreRemove
    public void delete() {
        this.deleted = true;
    }
//
    @PrePersist
    public void onCreate() {
        createTime = createTime == null ? LocalDateTime.now() : createTime;
        updateTime = updateTime == null ? LocalDateTime.now() : updateTime;
        try {
            if (StpUtil.isLogin()) {
                LoginUser loginUser = LoginHelper.getLoginUser();
                if (loginUser != null) {
                    createBy = loginUser.getUserId();
                    updateBy = loginUser.getUserId();
                }
            }
        } catch (Exception e) {
        }
//        if (status == null) {
//            status = 0;
//        }
    }

    @PreUpdate
    public void onUpdate() {
        updateTime = LocalDateTime.now();
        try {
            LoginUser loginUser = LoginHelper.getLoginUser();
            if (loginUser != null) {
                updateBy = loginUser.getUserId();
            }
        } catch (Exception e) {

        }
    }

}
